package com.weirong.smartvault.backservice.service;

import com.weirong.smartvault.dao.DictRepository;
import com.weirong.smartvault.entity.Dict;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import java.util.Date;

/**
 * 于2017/12/1由 KFEB4 创建 .
 */
@Service
public class DictServiceImpl implements DictService {
    private Specification<Dict> specification;
    @Autowired
    private DictRepository dictRepository;

    public DictServiceImpl() {
        specification = (root, criteriaQuery, criteriaBuilder) -> {
            Path<Date> parent_id = root.get("parentId");
            Predicate predicate = criteriaBuilder.isNull(parent_id);
            return criteriaBuilder.and(predicate);
        };
    }

    @Override
    public Page<Dict> findAllRootPageable(Integer page, Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(page, size, sort);
        return dictRepository.findAll(specification, pageable);

    }

    @Override
    public long countRoot() {
        return dictRepository.count(specification);
    }

    public String getNameByCode(String code) {
        Dict dict = this.dictRepository.findDictByCode(code);
        return dict.getName();
    }
}
